import 'package:dio/dio.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/UI/Loading.dart';

import 'dart:io';
import 'loading_page.dart';

import 'package:http/http.dart' as http;

var dio = new Dio();

class Method {
  static final String get = "GET";
  static final String post = "POST";
  static final String put = "PUT";
  static final String head = "HEAD";
  static final String delete = "DELETE";
  static final String patch = "PATCH";
}

class HttpHelper {
//  BuildContext context =this.context;
//  LoadingPage loadingPage = LoadingPage(context);
 // static const String host = 'http://ylz.9ok6.com'; //服务器
  static const String host = 'http://app.chemogu1688.com';//服务器
  static const String baseUrl = host + '/app/cmg_api.php?i=16&r=cmgapi.'; //请求路径

//API 列表
  static const String API_Reg = "regInspector"; //注册检测师
  static const String API_SendCode = "sendMsg"; //发送验证码
  static const String API_UserLog = "partnerlogin"; //合伙人登录
  
  static const String API_ResetPwd = "resetpartnerpassword"; //普通用户充值密码
  static const String API_FeeLog = "staff/login"; //收费员登录
  static const String API_FeeResetPwd = "staff/resetPassword"; //收费员忘记密码
  static const String API_AddCar = "car/addCar";
  static const String API_DeleCar = "car/delCar";
  static const String API_CarList = "car/carList";
  static const String API_AddOrder = "order/addOrder";
  static const String API_FeeOrderList = "order/staffOrderList"; //收费员收费记录
  static const String API_UserOrderList = "getMyOrder"; //城市合伙人订单列表
  static const String API_SiteOrder = "getSiteOrder";//获取站点订单
  static const String API_OrderDetail = "getOrderDetail";
  static const String API_UpLoadFile = "uploadPic";
  static const String API_AddressList = "staff/addressList";
  static const String API_payCode = "order/payQrcode";
  static const String API_OrderStatus = "order/orderStatus";
  static const String API_OrderPayStatus = "order/orderPayStatus";
  static const String API_CardList = "card/cardType"; //会员卡列表
  static const String API_MyCard = "card/applyCardList"; //我的会员卡
  static const String API_ApplyCard = "card/applyCard";
  static const String API_LevelNopay = "order/taoPiao";
  static const String API_Getshuiyin = "order/orderImages";
  static const String API_Userinfo = "partnerinfo"; //合伙人信息
  static const String API_Quelist = "getQuestion";
  static const String API_UpdateAvatar = "updateAvatar";
  static const String API_UpdateOrderStart = "setIsStart"; //设置开始检测
  static const String API_LoadTestItem = "getTestItems"; //加载检测项
  static const String API_SubOrder = "subOrder"; //提交检测项数据
  static const String API_DrawList = "getWithDrawList"; //提现记录
  static const String API_SubDrawApply = "submitWithDraw"; //提交提现申请
  static const String API_MyMoney = "getBalance"; //我的余额
  static const String API_Qrcode = "getpartnerQrCode"; //获取我的二维码
  static const String API_GetScore = "getScore"; //考试记录
  static const String API_GetExam = "goexam"; //考试题目
  static const String API_SubexamAns = "answer_question"; //考试题目
  static const String API_ApplyTest = "applyTest"; //申请补考
  static const String API_GetAsk = "getAnswers"; //回答详情列表
  static const String API_GetAskList = "getAnswerList"; //问答列表
  static const String API_GetAskDetail = "getQuestionDetail"; //问答详情
  static const String API_SubAskAns = "subComment"; //提交问答评论
  static const String API_SubAsk = "subAsk"; //发布问题
  static const String API_Dianzan = "dianzan"; //点赞问答
  static const String API_RegBussiness = "regBussiness"; //注册车商
  static const String API_LoginBusiness = "loginBusiness"; //车商登录
  static const String API_BusinessInfo = "businessinfo"; //车商个人信息
  static const String API_BussinessSuborder = "bussinessSuborder"; //车商 下检测订单
  static const String API_BussinessOrderDetail = "businessOrderDetail"; //车商订单详情
  static const String API_BussinessOrderList = "bussinessOrderList"; //车商订单列表
  static const String ApI_CarList = "carlist"; //车源列表
  static const String API_Brand = "getCarBrand"; //车辆品牌
  static const String API_CarType = "getcartype"; //车型
  static const String API_Guratee = "create_order"; //车商提交保修订单
  static const String API_SubOrderComnet = "comentorder"; //车商提交保修订单评加
//agreement
  static const String API_Agreement = "agreement"; //入驻协议

  static const String API_CancelTest = "reteststate"; //取消考试

  static const String API_GetInsurance = "getInsurance"; //获取保险公司数据

  static const String API_GetSites = "sites"; //获取站点
  static const String API_AddSite = "addsite"; //添加站点
  static const String API_SiteInfo = "siteinfo"; //站点信息
  static const String API_Assin = "assignOrder"; //指派订单
  static const String API_MyInspector = "myInspector"; //检测师列表
  static const String API_EditSite = "editSiteinfo"; //编辑站点
static const String API_Version = "remoteversion_P";//远程版本编号
  static const String API_OrderCount = "orderstatics"; //首页订单统计数量
  static const String API_Inspectorinfo = "inspectorinfo";
  static const String API_EditInspector = "editInspctor"; //编辑用户信息
  static const String API_Mybussiness = "mybussiness"; //合伙人车商
  static const String API_BussinessInfo = "bussinessinfo";
  static const String API_EditBussiness = "editBussinessInfo";
  static const String API_GetIncome = "getincome"; //获取收益
  static const String API_GetDraw = "getdrawhis"; //提现记录
  static const String API_IncomeList = "incomelist"; //收益明细
  static const String API_Order = "order/getorder";
  static const String API_BussinessFee = "getbussinessfee"; //检测费用信息
  static const String API_Inspectorreview = "inspectorreview";//检测师审核
  static const String API_GetWxInfo = "getAppWxUser";//code交换微信openid
  static const String API_ApplyTx = "applytx";//申请提现新街口
  static const String API_GetTroubleCode = "gettroublecode";//获取故障描述
  static const String API_WithdrawAcontInfo = "withdraw_info";//获取提现账户的历史信息
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods

  static void get(String url, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    if (params != null && params.isNotEmpty) {
      StringBuffer sb = new StringBuffer("?");
      params.forEach((key, value) {
        sb.write("$key" + "=" + "$value" + "&");
      });
      String paramStr = sb.toString();
      paramStr = paramStr.substring(0, paramStr.length - 1);
      url += paramStr;
    }
    try {
      http.Response res = await http.get(Uri.parse( baseUrl + url));
      if (callback != null) {
        final result = json.decode(res.body.toString());
        callback(result);
      }
    } catch (exception) {
      if (errorCallback != null) {
        errorCallback(exception);
      }
    }
  }
static void postRequest(String url, bool header, bool loading,
      BuildContext context, Function callback,
      {Map<String, Object> params, Function errorCallback}) async {
          try {
      EasyLoading.show(status: "");
      http.Response res = await http.post(Uri.parse(baseUrl + url), body: params);
      print('请求地址:' + baseUrl + url);
      EasyLoading.dismiss();
      if (callback != null) {
        final result = json.decode(res.body.toString());

        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
      }
  static void post(String url, Function callback,
      {Map<String, Object> params, Function errorCallback}) async {
    ///app/cmg_api.php?i=16&r=cmgapi.dianzan

    try {
     // EasyLoading.show(status: "");
      http.Response res = await http.post(Uri.parse(baseUrl + url), body: params);
      print('请求地址:' + baseUrl + url);
    //  EasyLoading.dismiss();
      if (callback != null) {
        final result = json.decode(res.body.toString());

        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  static void postUrl(String url, BuildContext context, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    print(params);

    LoadingPage loadingPage = LoadingPage(context);
    loadingPage.show();

    ///app/cmg_api.php?i=16&r=cmgapi.dianzan

    try {
      http.Response res = await http.post(Uri.parse(baseUrl + url), body: params);
      print('请求地址:' + baseUrl + url);
      loadingPage.close();
      if (callback != null) {
        final result = json.decode(res.body.toString());

        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  //转换百度地图位置信息
  static void PostLocation(Function callback,
      {Map<String, String> params}) async {
    String url = '';
    if (Platform.isIOS) {
      url =
          'http://api.map.baidu.com/reverse_geocoding/v3/?ak=hHqbyRqLANLY1rL0EU5C16jfDEyRhoCp&mcode=com.chemg.chemg&output=json&coordtype=wgs84ll&location=' +
              params['lat'] +
              ',' +
              params['lng'];
    } else if (Platform.isAndroid) {
      url =
          'http://api.map.baidu.com/reverse_geocoding/v3/?ak=qphSiTiHvW77B9xzMwqIQQauI4Q6edop&mcode=7D:70:CA:CB:71:3B:B5:4D:EA:14:81:33:45:BB:33:5A:16:BF:22:2E&output=json&coordtype=wgs84ll&location=' +
              params['lat'] +
              ',' +
              params['lng'];
    }
    http.Response res = await http.get(Uri.parse(url));
    print(url);
    if (callback != null) {
      final result = json.decode(res.body.toString());
      callback(result);
    }
  }

  static void postqrCode(String url, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    try {
      http.Response res = await http.post(
         Uri.parse( "https://www.kuaizhan.com/common/encode-png?large=true"),
          body: params);

      if (callback != null) {
        print('------------二维码响应结果------------');
        final result = json.decode(res.body.toString());
        print(result);
        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  static void upLoadImage(File image, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    // try {

    File _files = await FlutterNativeImage.compressImage(
      image.path,
      quality: 40,
    );
    String path = _files.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.fromMap(
        {"file": await MultipartFile.fromFile(path, filename: name)});

    Dio dio = new Dio();
    var respone =
        await dio.post<String>(baseUrl + API_UpLoadFile, data: formData);
    print('图片上传结果');
    if (callback != null) {
      final result = json.decode(respone.toString());
      print(result);
      callback(result);
    }
    // }catch(e){
    //   if (errorCallback != null) {
    //     errorCallback(e);
    //     print(e);
    //     print('-------异常--------');
    //   }
  }
}
// static Future uploadImg(imgfile) async{
//     String path = imgfile.path;
//     var name = path.substring(path.lastIndexOf("/") + 1, path.length);
//     FormData formData = new FormData.fromMap({
//       "file": new (new File(path), name)
//     });
//     Response response;
//     Dio dio =new Dio();
//     response =await dio.post(‘后端接口‘,data: formData);
//     if(response.statusCode == 200){
//       return response.data;
//     }else{
//       throw Exception(‘后端接口异常‘);
//     }
//   }
